# -*- coding: utf-8 -*-
import sys
import os
import hashlib
import time
import os
#import urllib2,json
import tornado.options
import tornado.ioloop
import tornado.web
import tornado.escape
from xml.etree import ElementTree as ET
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "./static/"),
    #"cookie_secret": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    "debug": True,
}

class MainHandler(tornado.web.RequestHandler):
    def parse_request_xml(self,rootElem):
        msg = {}
        if rootElem.tag == 'xml':
            for child in rootElem:
                msg[child.tag] = child.text  # 获得内容
        return msg
    def get(self):
        #获取输入参数
        signature=self.get_argument('signature','')
        timestamp=self.get_argument('timestamp','')
        nonce=self.get_argument('nonce','')
        echostr=self.get_argument('echostr','')
        #自己的token
        token="AAAAAAAAAAAAAAAAAAAAAAA" #这里改写你在微信公众平台里输入的token
        #字典序排序
        list=[token,timestamp,nonce]
        list.sort()
        sha1=hashlib.sha1()
        map(sha1.update,list)
        hashcode=sha1.hexdigest()
        #sha1加密算法
        #如果是来自微信的请求，则回复echostr
        if hashcode == signature:
            self.write(echostr)
    def post(self):
        rawstr = self.request.body
        msg = self.parse_request_xml(ET.fromstring(rawstr))
        MsgType = tornado.escape.utf8(msg.get("MsgType"))
        Content= tornado.escape.utf8(msg.get("Content"))
        FromUserName = tornado.escape.utf8(msg.get("FromUserName"))
        CreateTime = tornado.escape.utf8(msg.get("CreateTime"))
        ToUserName = tornado.escape.utf8(msg.get("ToUserName"))
        if MsgType != "text":
            Content= "Sorry，親，你的style我不懂！"
        if not Content:
            Content= "歡迎您使用！"
        data = '''<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
        </xml> ''' % (FromUserName,ToUserName,int(time.time()),'text',Content)
        self.write(data)        #提交信息
        
application = tornado.web.Application([
    (r"/", MainHandler),
    ], **settings)


if __name__ == "__main__":
    tornado.options.define("port", default=80, help="Run server on a specific port", type=int)
    tornado.options.parse_command_line()
    application.listen(tornado.options.options.port)
    tornado.ioloop.IOLoop.instance().start()
